/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.common.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.hanhai.common.annotation.LoginNeedless;
import com.hanhai.common.annotation.PermissionNeed;
import com.hanhai.common.enums.ErrorCode;

//常用的工具方法
public class CommonUtil {

	private static Logger logger = Logger.getLogger(CommonUtil.class);

	public static String hiddenName(String name) {
		if (StringUtils.isBlank(name) || name.length() <= 4) {
			return name;
		}
		String header = name.substring(0, 2);
		String end = name.substring(name.length() - 2, name.length());
		String hiddenName = header + "****" + end;
		return hiddenName;
	}

	// 修改nameList,返回同一个对象的引用
	public static List<String> hiddenName(List<String> nameList) {
		if (nameList == null || nameList.size() == 0) {
			return nameList;
		}
		int size = nameList.size();
		for (int index = 0; index < size; index++) {
			String name = nameList.get(index);
			String hiddenName = hiddenName(name);
			nameList.set(index, hiddenName);
		}
		return nameList;
	}

	
	public static void main(String[] args) {
		System.out.println(hiddenName("fansunion"));
		System.out.println(hiddenName("abG小雷a"));
		System.out.println(hiddenName("abGa"));

		Random rand = new Random();
		System.out.println(rand.nextInt(100));
        Integer n=RandomUtils.nextInt(100, 1000);
        System.out.println("3位数的随机数："+n);
        System.out.println("20位唯一时间戳："+uniqueNo());
	}
	


	public static String list2String(List<?> list, String separator) {

		StringBuilder builder = new StringBuilder();

		int size = list.size();
		for (int index = 0; index < size; index++) {
			if (index == 0) {
				Object str = list.get(index);
				builder.append(str);
			} else {
				Object str = separator + list.get(index);
				builder.append(str);
			}
		}
		String finalStr = builder.toString();
		return finalStr;

	}

	/**
	 * 20位的唯一数，前17位是系统当前时间，后3位是随机数。
	 */
	public static String uniqueNo() {
		String dateStr = DateFormatUtil.format(new Date(), "yyyyMMddHHmmssSSS");
		Integer threeRandomStr=RandomUtils.nextInt(100, 1000);
		return dateStr+threeRandomStr;
	}

	// 从请求中获得图片，存储，并返回图片名称，多个图片用“,”隔开
	public static String handleFileList(HttpServletRequest request,
			String imagePath) {
		String finalFileName = "";
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		// 取得request中的所有文件名
		Iterator<String> iter = multiRequest.getFileNames();
		while (iter.hasNext()) {
			// 取得上传文件
			MultipartFile file = multiRequest.getFile(iter.next());
			if (file != null) {
				// 取得当前上传文件的文件名称
				String fileName = file.getOriginalFilename();
				// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
				if (StringUtils.isNotEmpty(fileName)) {
					String[] strs = fileName.split("\\.");
					String fileExtention = "png";
					// 重命名上传后的文件名
					if (strs.length >= 2) {
						fileExtention = strs[strs.length - 1];
					}
					try {
						String randomName = uniqueNo();
						fileName = randomName + "." + fileExtention;
						finalFileName += fileName + ",";

						String path = imagePath + File.separator + fileName;
						File localFile = new File(path);
						file.transferTo(localFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return finalFileName;
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request){
		String requestedWith=request.getHeader("x-requested-with");  
		if(StringUtils.isEmpty(requestedWith)){
			return false;
		}else if(StringUtils.isNotEmpty(requestedWith) && requestedWith.equals("XMLHttpRequest")){
			return true;
		}
		return false;
	}

	public static String getRemoteIp(HttpServletRequest request) {
		String remoteIp = request.getHeader("x-forwarded-for");
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("X-Real-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("Proxy-Client-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("HTTP_CLIENT_IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteAddr();
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteHost();
		}
		if (remoteIp != null && remoteIp.indexOf(",") != -1) {
			remoteIp = remoteIp.substring(remoteIp.lastIndexOf(",") + 1,
					remoteIp.length()).trim();
		}
		return remoteIp;
	}
	
	public static void returnMessage(HttpServletResponse response, String content) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			pWriter.write(content);
		} catch (IOException e) {
			logger .error("returnMessage", e);
		} finally {
			if (pWriter != null) {
				pWriter.flush();
				pWriter.close();
			}
		}
	}

	public static boolean hasLoginNeedless(Object handler) {
		if(!(handler instanceof HandlerMethod)){
			return false;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Class<?> type = handlerMethod.getBeanType();
	
		// 判断是否需有loginNeedless标记
		LoginNeedless loginNeedless = type.getAnnotation(LoginNeedless.class);
		if (loginNeedless == null) {
			loginNeedless = type.getSuperclass().getAnnotation(
					LoginNeedless.class);
		}
		if (loginNeedless == null) {
			loginNeedless = handlerMethod
					.getMethodAnnotation(LoginNeedless.class);
		}
		return loginNeedless != null;
	}
	
	public static PermissionNeed extractPermissionNeed(Object handler) {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Class<?> type = handlerMethod.getBeanType();
	
		// 判断是否需有PermissionNeed标记
		PermissionNeed permissionNeed = type.getAnnotation(PermissionNeed.class);
		if (permissionNeed == null) {
			permissionNeed = type.getSuperclass().getAnnotation(
					PermissionNeed.class);
		}
		if (permissionNeed == null) {
			permissionNeed = handlerMethod
					.getMethodAnnotation(PermissionNeed.class);
		}
		return permissionNeed;
	}

	public static void jsonLogin(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", ErrorCode.NO_LOGIN.getCode());
		jsonObject.put("msg", "会话超时，请重新登录");
		returnMessage(response, jsonObject.toJSONString());
	}
	
	public static void jsonMobileLogin(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("res", ErrorCode.NO_LOGIN.getCode());
		jsonObject.put("msg", "会话超时，请重新登录");
		returnMessage(response, jsonObject.toJSONString());
	}

	public static void jsonNoPermission(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", ErrorCode.NO_PERMISSION.getCode());
		jsonObject.put("msg", "权限不足");
		returnMessage(response, jsonObject.toJSONString());
	}

	public static void jsonError(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", ErrorCode.SYSTEM_ERROR.getCode());
		jsonObject.put("msg", "系统内部错误");
		returnMessage(response, jsonObject.toJSONString());
	}
	
	public static void jsonApiError(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("res", ErrorCode.SYSTEM_ERROR.getCode());
		jsonObject.put("msg", "系统内部错误");
		returnMessage(response, jsonObject.toJSONString());
	}

	public static void jsonMobileOtherLogin(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("res", ErrorCode.OTHER_LOGIN.getCode());
		jsonObject.put("msg", "您的账号在其他地方登录");
		returnMessage(response, jsonObject.toJSONString());
	}

	public static void jsonMobileBlacklist(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("res", ErrorCode.SYSTEM_ERROR.getCode());
		jsonObject.put("msg", "黑名单用户，无法正常访问");
		returnMessage(response, jsonObject.toJSONString());
		
	}
	
}
